package org.duang.kit;

import java.util.HashMap;
import java.util.Map;

import org.duang.common.exceptios.ServiceException;
import org.duang.pay.core.IPayRequest;
import org.duang.pay.core.PayFactory;

/**
 * 支付工具，提供取提交给第三方支付平台信息及验证签名两个方法
 * @author laotang
 *
 */
public class PayKit {
	private static java.util.concurrent.locks.ReentrantLock lock = new java.util.concurrent.locks.ReentrantLock();
	private static PayKit payKit;
	private static IPayRequest payRequest;
	private static Map<String,Object> map = new HashMap<String,Object>();
	
	private PayKit() {
	}
	
	public static PayKit duang() {
		synchronized (lock) {
			if (null == payKit) {
				payKit = new PayKit();				
			}
		}
		map.clear();
		payRequest = null;
		return payKit;
	}
	
	
	/**
	 * 设置支付对象
	 * @param key				名称
	 * @param value			值内容
	 * @return
	 */
	public PayKit param(IPayRequest request) {
		payRequest = request;
		return this;
	} 
	
	public PayKit param(Map<String,Object> paramMap) {
		map.putAll(paramMap);
		return this;
	} 
	
	/**
	 * 返回支付所需要的字符串
	 * @return		字符串
	 */
	public String result() {
		return PayFactory.getResult(payRequest);
	}
	
	/**
	 * 验证签名是否正确
	 * @return		正确返回true
	 */
	public boolean checkSgin() {
		String sgin = sgin();
		return ToolsKit.isNotEmpty(sgin) ? true : false;
	}
	
	/***
	 * 取得签名值
	 * @return
	 */
	public String sgin() {
		if(ToolsKit.isNotEmpty(payRequest)  && ToolsKit.isNotEmpty(map)) {
			System.out.println("#############: PayKit.duang().param()方法分别设置了payRequest及map，最终以设置payRequest为准!");
			map.clear();
		}
		
		if(ToolsKit.isNotEmpty(payRequest)) {
			map.putAll(ObjectKit.getFieldMap(payRequest));
		}
		return PayFactory.sign(map);
	}
	
	/**
	 * 發红包
	 * @return
	 */
	public String redpack() {
		return PayFactory.redpack(payRequest);
	}
	
	// https://pay.weixin.qq.com/wiki/doc/api/tools/cash_coupon.php?chapter=13_6&index=5
	public String hbinfo() {
		return PayFactory.hbinfo(payRequest);
	}
}

